<?php
/* 
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

defined('IN_ADMIN') or die('Hacking Attempt!');

func::isLogin();
mysql::begin(1);

$sTable = 'tnf.order';
$iTotal = 0;

if(isset($_POST['addOrderButton'])){
    $aTotal = isset($_POST['val']) ? func::replaceNumberFormat($_POST['val']) : array(array());
    
    
    for($i=0; $i < (int)((count($aTotal, 1) - 3) / 3); $i++){
        //prepare date
        $iIdInvent = explode('.', $aTotal['inventoryId'][$i]);
        $aInventory['inventoryId'][$i] = $iIdInvent[0];
        $iQuantity = is_numeric($aTotal['quantity'][$i]) ? $aTotal['quantity'][$i] : 0;
        $iPrice = is_numeric($aTotal['price'][$i]) ? $aTotal['price'][$i] : 0;

        //calculate total amount
        $iTotal += $iQuantity * $iPrice;
    }

    $aVals = array(
        'customerId' => isset($_POST['customerId']) ? $_POST['customerId'] : 0,
        'total' => $iTotal,
        'content' => serialize(isset($_POST['val']) ? $_POST['val'] : array(array())),
        'delivered' => isset($_POST['delivered']) ? $_POST['delivered'] : 0,
        'date' => time(),
        'username' => $_SESSION[SESSION_NAME]
   );

   $iIdInsertOrder = mysql::insertSql($sTable, $aVals);

   //get current debit amount
   $aRow = mysql::selectDebitAmount('debit', $aVals['customerId']);
   $iTotal += $aRow['amount'];
   $iIdUpdateDebit = mysql::updateSql('debit', array('amount' => $iTotal), 'customerId', $aVals['customerId']);

   //update inventory
   foreach($aInventory['inventoryId'] as $key=>$value){
       $aRow = mysql::selectInventoryQuantity('inventory', $value);
       //check if enough quantity
       $iInventoryQuantity = $aRow['quantity'] - $aTotal['quantity'][$key];

       if($iInventoryQuantity > 0)
            $iIdUpdateInventory = mysql::updateSql('inventory', array('quantity' => $iInventoryQuantity), 'inventoryId', $value);
       else
           die($aRow['title'].' không còn đủ hàng để bán.');
   }

   if($iIdInsertOrder && $iIdUpdateDebit && $iIdUpdateInventory){
       mysql::commit();
       func::redirect(func::makeUrl ('order', 'list'));
   }else
       mysql::rollBack();
} else{
    //get customer list field
    $sSql = "SELECT customerId, name FROM customer ORDER BY name ASC";
    $aCustomer = mysql::querySql($sSql);

    //get inventory list field
    $sSql = "SELECT inventoryId, title FROM inventory ORDER BY title ASC";
    $aInventory = mysql::querySql($sSql);
}
?>
